<template>
  <div class="homework-list-container">
    <div class="header-actions">
      <h2>我的作业</h2>
      <el-select v-model="filterStatus" placeholder="状态筛选" @change="handleFilterChange">
        <el-option label="全部" value="" />
        <el-option label="未提交" value="0" />
        <el-option label="已提交" value="1" />
        <el-option label="已批改" value="2" />
      </el-select>
    </div>

    <el-table :data="homeworkList" v-loading="loading" border stripe>
      <el-table-column prop="title" label="作业标题" min-width="180" />
      <el-table-column prop="className" label="班级" width="120" />
      <el-table-column prop="subjectName" label="学科" width="120" />
      <el-table-column prop="endTime" label="截止日期" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="score" label="得分" width="100">
        <template #default="scope">
          <span v-if="scope.row.status === 2">{{ scope.row.score }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleViewHomework(scope.row)"
            link
          >
            查看
          </el-button>
          <el-button 
            v-if="scope.row.status === 0 && !isHomeworkExpired(scope.row.endTime)"
            type="success" 
            size="small" 
            @click="handleSubmitHomework(scope.row)"
            link
          >
            提交
          </el-button>
          <el-button 
            v-if="scope.row.status === 1"
            type="warning" 
            size="small" 
            @click="handleModifySubmission(scope.row)"
            link
          >
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="total > 0"
      class="pagination"
      :total="total"
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getStudentHomeworks } from '@/api/homework'
import { useRouter } from 'vue-router'
import { formatDate } from '@/utils/format'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()
const homeworkList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const filterStatus = ref('')

// 获取作业列表
const fetchHomeworkList = async () => {
  loading.value = true
  try {
    const studentId = userStore.userId
    console.log('获取学生作业列表，学生ID:', studentId)
    
    const res = await getStudentHomeworks(
      studentId, 
      currentPage.value, 
      pageSize.value, 
      null // 不传递标题搜索参数
    )
    
    if (res.code === 200) {
      console.log('原始接口返回数据:', res.data)
      
      // 服务器返回的数据
      let data = res.data.records || [];
      
      // 处理作业状态
      data = data.map(item => {
        // 先记录原始状态用于调试
        const originalStatus = item.status;
        const hasSubmission = !!item.submissionId;
        
        // 状态处理逻辑:
        // 1. 有提交ID且状态为1 => 已批改(2)
        // 2. 有提交ID但状态不为1 => 已提交(1)
        // 3. 无提交ID => 未提交(0)
        let newStatus = 0;
        if (hasSubmission) {
          newStatus = item.status === 1 ? 2 : 1;
        }
        
        console.log(`作业[${item.id}]: 原状态=${originalStatus}, 有提交=${hasSubmission}, 新状态=${newStatus}`)
        
        return { 
          ...item, 
          status: newStatus,
          // 确保显示分数，仅当状态为已批改(2)时才显示分数
          score: newStatus === 2 ? item.score : null
        };
      });
      
      // 如果设置了状态筛选，在前端过滤结果
      if (filterStatus.value !== '') {
        const statusInt = parseInt(filterStatus.value);
        console.log('应用状态过滤:', statusInt)
        data = data.filter(item => item.status === statusInt);
        total.value = data.length; // 更新筛选后的总数
      } else {
        total.value = res.data.total || 0;
      }
      
      homeworkList.value = data;
      console.log('最终处理后的数据:', data)
    } else {
      ElMessage.error(res.message || '获取作业列表失败')
    }
  } catch (error) {
    console.error('获取作业列表失败', error)
    ElMessage.error('获取作业列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查看作业
const handleViewHomework = (row) => {
  router.push(`/student/homework-detail/${row.id}`)
}

// 处理提交作业
const handleSubmitHomework = (row) => {
  router.push(`/student/homework-submit/${row.id}`)
}

// 处理修改作业提交
const handleModifySubmission = (row) => {
  router.push(`/student/homework-submit/${row.id}?edit=true`)
}

// 获取作业状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'danger',   // 未提交
    1: 'warning',  // 已提交
    2: 'success'   // 已批改
  }
  return statusMap[status] || 'info'
}

// 获取作业状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未提交',
    1: '已提交',
    2: '已批改'
  }
  return statusMap[status] || '未知'
}

// 判断作业是否已过期
const isHomeworkExpired = (endTime) => {
  return new Date(endTime) < new Date()
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchHomeworkList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchHomeworkList()
}

// 筛选状态变化
const handleFilterChange = () => {
  currentPage.value = 1
  fetchHomeworkList()
}

onMounted(() => {
  fetchHomeworkList()
})
</script>

<style scoped>
.homework-list-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  width: 100%;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style> 